package wqh.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wqh.domain.Role;
import wqh.domain.User;
import wqh.global.GlobalSession;
import wqh.pojo.MapRet;
import wqh.service.RoleService;
import wqh.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/json/user")
public class UserJSONController {

    private static Logger logger = LoggerFactory.getLogger(UserJSONController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object insert(@RequestBody User user)
    {
        if(user.getUser() == null || user.getPassword() == null) return MapRet.SQL_ERROR("请输入用户名和密码。");
        try{
            logger.info("添加用户信息：" + user.toString());
            User find = new User();
            find.setUser(user.getUser());
            if(userService.findAllByObject(find).size() != 0)
            {
                return MapRet.SQL_ERROR(user.getUser() + "已存在");
            }
            userService.insertRecord(user);
            return MapRet.SQL_INSERT_SUCCESS();
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("添加用户信息失败：" + e);
            return MapRet.SQL_INSERT_ERROR();
        }
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(@RequestBody User user)
    {
        if(user.getId() == null) return MapRet.DATA_ERROR("id不存在");
        try{
            logger.info("修改用户信息：" + user.toString());
            userService.updateDataById(user);
            return MapRet.SQL_UPDATE_SUCCESS();
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.info("修改用户信息失败：" + e);
            return MapRet.SQL_UPDATE_ERROR();
        }
    }

    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    public Object updatePassword(HttpServletRequest request,
                                 @RequestParam(value = "oldPass",required = true) String oldPass,
                                 @RequestParam(value = "newPass",required = true) String newPass)
    {

        try{
            String userName = GlobalSession.getUserNameBySessionID(request.getSession().getId());
            User oldUser = new User();
            oldUser.setUser(userName);
            oldUser.setPassword(oldPass);
            List<User> userList = userService.findAllByObject(oldUser);
            if(userList.size() == 0) return MapRet.DATA_ERROR("旧密码不匹配");
            User newUser = new User();
            newUser.setId(userList.get(0).getId());
            newUser.setPassword(newPass);
            userService.updateDataById(newUser);
            return MapRet.SQL_UPDATE_SUCCESS();
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.info("修改用户密码失败：" + e);
            return MapRet.SQL_UPDATE_ERROR();
        }
    }

    @RequestMapping(value = "/updatePicture",method = RequestMethod.POST)
    public Object updatePicture(HttpServletRequest request, @RequestParam(value = "file",required = true)MultipartFile file)
    {
        try {
            String userName = GlobalSession.getUserNameBySessionID(request.getSession().getId());
            User find = new User();
            find.setUser(userName);
            List<User> userList = userService.findAllByObject(find);
            if(userList.size() == 0) return MapRet.DATA_ERROR("用户不存在");

            String localPath = "upload\\userPicture\\";
            String uploadPath = request.getServletContext().getRealPath("/");

            if(userList.get(0).getPicture() != null && userList.get(0).getPicture().length() != 0 && !userList.get(0).getPicture().equals("0"))
            {
                String serverPath = uploadPath +userList.get(0).getPicture();
                File serverFile = new File(serverPath);
                if(serverFile.isFile() && serverFile.exists())
                {
                    serverFile.delete();
                }
            }

            File uploadDir = new File(uploadPath + localPath);
            if(!uploadDir.exists())
            {
                uploadDir.mkdirs();
            }
            String fileName = file.getOriginalFilename();
            if(fileName != null)
            {
                byte[] bytes = file.getBytes();
                fileName = System.currentTimeMillis() + fileName;
                File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                User updateUser = userList.get(0);
                updateUser.setPicture(localPath + serverFile.getName());
                userService.updateDataById(updateUser);
            }
            return MapRet.SQL_UPDATE_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("更新用户头像异常：" + e);
            return MapRet.SQL_UPDATE_ERROR();
        }
    }

    @RequestMapping(value = "/getUserList",method = RequestMethod.GET)
    public Object getUserList(HttpServletRequest request)
    {
        try {
            List<Object> objectList = new ArrayList<Object>();
            String userName = GlobalSession.getUserNameBySessionID(request.getSession().getId());
            User find = new User();
            find.setUser(userName);
            List<User> userList = userService.findAllByObject(find);
            if(userList.size() == 0) return MapRet.SQL_ERROR();
            List<User> userAllList = userService.findAllRecord();
            for(User user : userAllList){
                if(user.getRole_id().equals(userList.get(0).getRole_id())) continue;
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("id",user.getId());
                map.put("text",user.getUser() +"____"+user.getName());
                objectList.add(map);
            }
            return MapRet.DATA(objectList);
        }catch (Exception e)
        {
            e.printStackTrace();
            return MapRet.SQL_ERROR();
        }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object delete(HttpServletRequest request,@RequestParam(value = "id",required = true) int id)
    {
        try{
            User user = userService.findAllById(id);
            if(user == null) return MapRet.SQL_ERROR("id不存在");
            String uploadPath = request.getServletContext().getRealPath("/");
            if(user.getPicture() != null && user.getPicture().length() != 0 && !user.getPicture().equals("0"))
            {
                String serverPath = uploadPath +user.getPicture();
                File serverFile = new File(serverPath);
                if(serverFile.isFile() && serverFile.exists())
                {
                    serverFile.delete();
                }
            }
            userService.deleteById(id);
            return MapRet.SQL_DELETE_SUCCESS();
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.info("删除用户信息失败：" + e);
            return MapRet.SQL_DELETE_ERROR();
        }
    }

    @RequestMapping(value = "/online",method = RequestMethod.GET)
    public Object online()
    {
        try {
            User online = new User();
            online.setOnline((byte)1);
            return MapRet.DATA(userService.findAllByObject(online));
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("查询错误" + e);
            return MapRet.SQL_ERROR("查询错误");
        }
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public Object addUser(HttpServletRequest request,
                          @RequestParam(value = "role",required = true) int role_id,
                          @RequestParam(value = "name",required = true) String user_name,
                          @RequestParam(value = "password",required = true) String password,
                          @RequestParam(value = "passwordConfirm",required = true) String passwordConfirm,
                          @RequestParam(value = "chineseName",required = true) String chinese_name,
                          @RequestParam(value = "gender",required = true) byte gender,
                          @RequestParam(value = "contact",required = true) String contact,
                          @RequestParam(value = "file",required = false,defaultValue = "null") MultipartFile file)
    {
        try {
            User find = new User();
            find.setUser(GlobalSession.getUserNameBySessionID(request.getSession().getId()));
            List<User> userList = userService.findAllByObject(find);
            if(userList.size() == 0) return MapRet.SQL_INSERT_ERROR();
            if(userList.get(0).getRole_id() >= role_id) return MapRet.SQL_INSERT_ERROR();
            if(userList.get(0).getName().equals(chinese_name)) return MapRet.SQL_INSERT_ERROR();
            if(password == null ? passwordConfirm != null : !password.equals(passwordConfirm)) return MapRet.SQL_INSERT_ERROR();
            User newUser = new User();
            newUser.setRole_id(role_id);
            newUser.setUser(user_name);
            newUser.setPassword(password);
            newUser.setName(chinese_name);
            newUser.setGender(gender);
            newUser.setContact(contact);
            newUser.setRegistered_time((int)System.currentTimeMillis() / 1000);
            if(file != null){
                String localPath = "upload\\userPicture\\";
                String uploadPath = request.getServletContext().getRealPath("/");
                File uploadDir = new File(uploadPath + localPath);
                if(!uploadDir.exists())
                {
                    uploadDir.mkdirs();
                }
                String fileName = file.getOriginalFilename();
                if(fileName != null)
                {
                    byte[] bytes = file.getBytes();
                    fileName = System.currentTimeMillis() + fileName;
                    File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    newUser.setPicture(localPath + serverFile.getName());
                }
            }
            userService.insertRecord(newUser);
            return MapRet.SQL_INSERT_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("新添用户异常：" + e);
            return MapRet.SQL_INSERT_ERROR();
        }
    }


}
